package com.ict.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ict.api.dto.IctRoleDTO;
import com.ict.api.entity.IctRole;
import com.ict.api.entity.IctUserRole;
import com.ict.api.vo.IctRoleVO;
import com.ict.mapper.IctRoleMapper;
import com.ict.mapper.IctUserRoleMapper;
import com.ict.service.IctRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author wjp
 * @since 2025-03-23
 */
@Service
public class IctRoleServiceImpl extends ServiceImpl<IctRoleMapper, IctRole> implements IctRoleService {

    @Resource
    private IctUserRoleMapper userRoleMapper;

    @Resource
    private IctRoleMapper roleMapper;

    @Override
    public void setUserRoles(Long id, IctRoleDTO roleDTO) {
        List<Long> roleIds = roleDTO.getRoleIds();
        for (Long roleId : roleIds) {
            IctRole ictRole = roleMapper.selectOne(new LambdaQueryWrapper<IctRole>().eq(IctRole::getId, roleId));

            LambdaQueryWrapper<IctUserRole> lqw = new LambdaQueryWrapper<>();
            lqw.eq(IctUserRole::getRoleId, roleId);
            lqw.eq(IctUserRole::getUserId, id);
            IctUserRole ictUserRole = userRoleMapper.selectOne(lqw);
            if (ictUserRole == null) {
                // 新增角色
                ictUserRole = new IctUserRole();
                ictUserRole.setUserId(id);
                ictUserRole.setRoleId(roleId);
                ictUserRole.setRoleName(ictRole.getRoleName());
                userRoleMapper.insert(ictUserRole);
            }
        }
    }

    @Override
    public List<IctRoleVO> getRoles() {
        List<IctRole> ictRoles = roleMapper.selectList(null);
        List<IctRoleVO> roleVoList = ictRoles.stream().map(item -> {
            IctRoleVO ictRoleVo = new IctRoleVO();
            BeanUtils.copyProperties(item, ictRoleVo);
            return ictRoleVo;
        }).collect(Collectors.toList());
        return roleVoList;
    }

    @Override
    public void deleteUserRoles(Long id, IctRoleDTO roleDTO) {
        LambdaQueryWrapper<IctUserRole> lqw = new LambdaQueryWrapper<>();
        lqw.in(IctUserRole::getRoleId, roleDTO.getRoleIds());
        lqw.eq(IctUserRole::getUserId, id);
        userRoleMapper.delete(lqw);
    }
}
